
import WebSocket from "ws";


import { getWindow,getWindowMangae }  from "./windowProxy";



let ws = null;
const maxRetires = 5;
let retryCount = 0;
const HEARTBEAT_INTERVAL = 5000;
let heartBeatTimer = null;
const retryInterval = 2000;
let wsUrl = null;
let needReconnect = null;


const initWs = (_wsUrl)=>{
  wsUrl = _wsUrl;
  needReconnect = true;
  connectWs();
}

const wsCheck = ()=>{
  return import.meta.env.VITE_WS_CHECK === "true";
}


const connectWs = ()=>{
    if(ws && (ws.readyState === WebSocket.OPEN || ws.readyState ===WebSocket.CONNECTING)){
        console.log("ws is already connected");
    }
    console.log(`try to connect ws(重试次数：${retryCount} / ${maxRetires}),连接地址：${wsUrl}`);
    ws = new WebSocket(wsUrl);
    ws.onopen = ()=>{
          if(retryCount > 0 && wsCheck){
              const mainWindow = getWindow("main");
              mainWindow.webContents.send("reconnect",true);
          }

          retryCount = 0;
          console.log("ws connected");

          startHeartBeat();
    }

    ws.onmessage =(event)=>{
       const data = JSON.parse(event.data);
       console.log("收到ws的消息",data);
    }

    ws.onerror=()=>{
      ws.close();
    }
    ws.onclose = ()=>{
      clearHeartBeatTimers();
      handleReconnect();
    }

  }

const handleReconnect =()=>{
  if(!needReconnect){
     return;
  }
  if(retryCount >= maxRetires){
      console.error("ws已经连接达到最大次数，放弃重连")
      retryCount = 0;
      if(wsCheck){
        logout(false);
      }
      return;
  }
  retryCount +=1;
  const delay =retryInterval * Math.pow(1.5,retryCount-1);
  console.log(`连接断开,等待${delay /1000}秒后重试`)
  if(wsCheck){
       const mainWindow = getWindow("main");
       mainWindow.webContents.send("reconnect",true);
  }

  setTimeout(()=>{
      connectWs();
   },delay)


}



const logout = (closeWs = true)=>{
    const login_width = 375;
    const login_height = 365;
    const mainWindow = getWindow("main");
    mainWindow.setResizable(true);
    mainWindow.setMinimumSize(login_width,login_height);
    mainWindow.setSize(login_width,login_height);
    mainWindow.setResizable(false);
    if(closeWs){
      needReconnect = false;
      ws.close();
    }

    const windows = getWindowMangae();

    for(let key in windows){
        const window = windows[key];
        if(key != "main"){
             window.close();
        }
    }
    mainWindow.webContents.send("logout");
}


const startHeartBeat =()=>{
   heartBeatTimer = setInterval(()=>{
   if(ws ?.readyState === WebSocket.OPEN){
      ws.send("ping")
   }
},HEARTBEAT_INTERVAL)
}

const clearHeartBeatTimers =()=>{
  clearInterval(heartBeatTimer);
  heartBeatTimer = null;
}


const sendWsData = (data)=>{
   if(!ws){
      return;
   }
   ws.send(data);
}

export {
  initWs,logout,sendWsData
}
